package org.jeecgframework.web.controller;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsAppKnowledgeServiceI;
import org.jeecgframework.web.system.pojo.base.CbsAppKnowledgeEntity;
import org.jeecgframework.web.system.pojo.base.TSRole;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSTypegroup;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 知识库
 * @date 2016-08-05 14:37:53
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsAppKnowledgeController")
public class CbsAppKnowledgeController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsAppKnowledgeController.class);

    @Autowired
    private CbsAppKnowledgeServiceI cbsAppKnowledgeService;
    @Autowired
    private SystemService systemService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 知识库列表 页面跳转
     */
    @RequestMapping(params = "cbsAppKnowledge")
    public ModelAndView cbsAppKnowledge(HttpServletRequest request) {
        return new ModelAndView("com/app/cbs_app_knowledge/cbsAppKnowledgeList");
    }

    /**
     * easyui AJAX请求数据
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsAppKnowledgeEntity.class, dataGrid);
        try {

            Map<String,String[]> params = new HashMap<String, String[]>();
            params.putAll(request.getParameterMap());

            if(params.containsKey("roleName")&&StringUtil.isNotEmpty(params.get("roleName"))){
                String sql = " 1=1 ";
                String strings = params.get("roleName")[0];
                if(StringUtil.isNotEmpty(strings)){
                    //防止sql自动注入Like %%查询
                    params.remove("roleName");
                    cq.like("roleName", "");
                    params.remove("roleid");
                    cq.like("roleid", "");

                    sql +="and (";
                    for (int i = 0; i < strings.split(",").length; i++) {
                        if (i == 0) {
                            sql += "roleName like '%" + strings.split(",")[i] + "%'";
                        } else {
                            sql += "or roleName like '%" + strings.split(",")[i] + "%'";
                        }
                    }
                    sql +=")";
                }
                cq.add(Restrictions.sqlRestriction(sql));
            }

            cbsAppKnowledge.setRoleid(null);
            cbsAppKnowledge.setRoleName(null);
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsAppKnowledge, params);
            this.cbsAppKnowledgeService.getDataGridReturn(cq, true);
            TagUtil.datagrid(response, dataGrid);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 知识库新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsAppKnowledge.getId())) {
            cbsAppKnowledge = cbsAppKnowledgeService.getEntity(CbsAppKnowledgeEntity.class, cbsAppKnowledge.getId());
            req.setAttribute("cbsAppKnowledgePage", cbsAppKnowledge);
        }
        //根据字典表查询知识类别
        List<TSType> dataList = TSTypegroup.allTypes.get(StaticValue.Know_Ledge_TYPE.toLowerCase());
        req.setAttribute("dataList", dataList);


        return new ModelAndView("com/app/cbs_app_knowledge/cbsAppKnowledge-add");
    }


    /**
     * 添加知识库
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "知识库添加成功";
        List<CbsAppKnowledgeEntity> cbsAppKnowledges = systemService.findByProperty(CbsAppKnowledgeEntity.class, "no", cbsAppKnowledge.getNo());
        if (cbsAppKnowledges.size() > 0) {
            message = "添加失败！知识库编号不能重复";
        } else {
            try {
                cbsAppKnowledgeService.save(cbsAppKnowledge);
                systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "知识库添加失败";
                throw new BusinessException(e.getMessage());
            }
        }

        j.setMsg(message);
        return j;
    }

    /**
     * 知识库编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsAppKnowledge.getId())) {
            cbsAppKnowledge = cbsAppKnowledgeService.getEntity(CbsAppKnowledgeEntity.class, cbsAppKnowledge.getId());
            String roleid = cbsAppKnowledge.getRoleid();
            String roleIds = "";
            if (null != roleid) {
                int i = roleid.indexOf(",");
                if (i != -1) {
                    String[] split = roleid.split(",");
                    for (int j = 0; j < split.length; j++) {
                        roleIds = roleIds + "'" + split[j] + "',";
                    }
                    roleIds = roleIds.substring(0, roleIds.length() - 1);
                } else {
                    roleIds = "'" + roleid + "'";
                }
                List<TSRole> roleList = systemService.findHql("from TSRole where id in (" + roleIds + ")");
                String roleName = "";
                for (TSRole role : roleList) {
                    roleName = roleName + role.getRoleName() + ",";
                }
                cbsAppKnowledge.setRoleName(roleName);
                req.setAttribute("id", roleid);
                req.setAttribute("roleName", roleName);
            }
            req.setAttribute("cbsAppKnowledgePage", cbsAppKnowledge);

        }
        //根据字典表查询知识类别
        List<TSType> dataList = TSTypegroup.allTypes.get(StaticValue.Know_Ledge_TYPE.toLowerCase());
        req.setAttribute("dataList", dataList);
        return new ModelAndView("com/app/cbs_app_knowledge/cbsAppKnowledge-update");
    }

    /**
     * 更新知识库
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "知识库更新成功";
        Boolean flage = false;
        CbsAppKnowledgeEntity t = cbsAppKnowledgeService.get(CbsAppKnowledgeEntity.class, cbsAppKnowledge.getId()); //库里面的
        List<CbsAppKnowledgeEntity> cbsAppKnowledges = systemService.findByProperty(CbsAppKnowledgeEntity.class, "no", cbsAppKnowledge.getNo());//修改
        if (cbsAppKnowledges.size() > 0) {
            for (CbsAppKnowledgeEntity appKnowledge : cbsAppKnowledges) {
                String oldid = appKnowledge.getId();
                if (!oldid.equals(t.getId())) {
                    flage = true;
                    break;
                }
            }
            if (!flage) {
                try {
                    MyBeanUtils.copyBeanNotNull2Bean(cbsAppKnowledge, t);
                    cbsAppKnowledgeService.saveOrUpdate(t);
                    systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
                } catch (Exception e) {
                    e.printStackTrace();
                    message = "知识库更新失败";
                    throw new BusinessException(e.getMessage());
                }
            } else {
                message = "知识库更新失败,知识库编号不能重复!";
            }
        } else if (cbsAppKnowledges.size() == 0) {
            try {
                MyBeanUtils.copyBeanNotNull2Bean(cbsAppKnowledge, t);
                cbsAppKnowledgeService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "知识库更新失败";
                throw new BusinessException(e.getMessage());
            }
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除知识库
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsAppKnowledgeEntity cbsAppKnowledge, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsAppKnowledge = systemService.getEntity(CbsAppKnowledgeEntity.class, cbsAppKnowledge.getId());
        message = "知识库删除成功";
        try {
            cbsAppKnowledgeService.delete(cbsAppKnowledge);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "知识库删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除知识库
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "知识库删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsAppKnowledgeEntity cbsAppKnowledge = systemService.getEntity(CbsAppKnowledgeEntity.class, id);
                cbsAppKnowledgeService.delete(cbsAppKnowledge);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "知识库删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * @author xiul
     * 2016-8-5 下午2:24:44
     * Description APP 端 - 知识库
     */
    @RequestMapping(params = "appKnowledge")
    public ModelAndView appKnowledge(HttpServletRequest req) {
        return new ModelAndView("com/app/cbs_app_knowledge/appKnowledge-list");
    }

    /**
     * @author xiul
     * 2016-8-5 下午3:21:18
     * Description APP 端 - 知识库列表加载方法
     */
    @ResponseBody
    @RequestMapping(params = "appKnowLedgeList")
    public AjaxJson appKnowLedgeList(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            List<Map<String, Object>> mapList = cbsAppKnowledgeService.queryAppKnowledge(req);
            j.setObj(mapList);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("加载失败");
        }
        return j;
    }

    /**
     * @author xiul
     * 2016-8-5 下午3:04:49
     * Description APP端 - 查看知识库详细
     */
    @ResponseBody
    @RequestMapping(params = "viewAppKnowLedge")
    public AjaxJson viewAppKnowLedge(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = oConvertUtils.getString(req.getParameter("id"));
        Map<String, Object> rtMap = cbsAppKnowledgeService.queryKnowledgeById(id);
        j.setAttributes(rtMap);
        return j;
//		req.setAttribute("knowLedge", knowLedge);
//		return new ModelAndView("com/app/cbs_app_knowledge/appKnowledge-view");
    }
}
